package com.roc.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

 

/**
*@auhor   zbl
*@date    2017年2月10日 下午2:53:49
*@desc    说明
**/
public class NewFtpUtils {
	private static Logger logger=Logger.getLogger(NewFtpUtils.class);
	
	/**
	 *处理文件上传至ftp服务器
	 * */
	public static boolean   handleFiles(File file,String path,String name){
		  boolean result=false;
		  String ip =Utils.getConfigValue("FTP_URL");// 服务器IP地址
		  String userName =  Utils.getConfigValue("FTP_USER");// 用户名
		  String userPwd =  Utils.getConfigValue("FTP_PASSWORD"); // 密码
		  int port = 21;// 端口号
		  String filePath=Utils.getConfigValue("FTP_REMOTE_FILEPATH")+"/"+path;
		  try {
			  result=connectServer(ip, port, userName, userPwd, filePath,file,name);
		} catch (Exception e) {
			result=false;
			logger.error(e.getMessage(),e);
		}
		  return result;
	}
	
	/**
	 * 处理云商宝文件上传至ftp服务器
	 * @param file
	 * @param path
	 * @param name
	 * @return
	 */
	public static boolean handleYsbFiles(File file,String path,String name){
		boolean result=false;
		String ip =Utils.getConfigValue("FTP_URL");// 服务器IP地址
		String userName =  Utils.getConfigValue("FTP_USER");// 用户名
		String userPwd =  Utils.getConfigValue("FTP_PASSWORD"); // 密码
		int port = 21;// 端口号
		String filePath=Utils.getConfigValue("FTP_REMOTE_FILEPATH")+"/"+Utils.getConfigValue("REALNAMR_AUTH")+"/"+path;
		try {
			result=connectServer(ip, port, userName, userPwd, filePath,file,name);
		} catch (Exception e) {
			result=false;
			logger.error(e.getMessage(),e);
		}
		  return result;
	}
	
	/**
	 * @param ip
	 * @param port
	 * @param userName
	 * @param userPwd
	 * @param path
	 * 连接服务器
	 */
	public static boolean connectServer(String ip, int port, String userName, String userPwd, String path,File file,String fileName) {
		boolean returnResult=false;
		FTPClient  ftpClient=null;
		FileInputStream input=null;
		try {
			ftpClient= new FTPClient();
			// 连接
			ftpClient.connect(ip, port);
			// 登录
			returnResult=ftpClient.login(userName, userPwd);
			if(returnResult==false){
				logger.info("---上传图片登陆FTP失败----");
				return returnResult;
			}
			//ftpClient.enterLocalPassiveMode();//bd
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//2jz  
            ftpClient.enterLocalActiveMode();//zd
            ftpClient.setRemoteVerificationEnabled(false);   
            
            int reply = ftpClient.getReplyCode();  
		    if (!FTPReply.isPositiveCompletion(reply)) {  
		    	ftpClient.disconnect();  
		        logger.info("##########FTP获得响应失败##########");
		        return false;  
		    }
			if (path != null && path.length() > 0) {
				// 跳转到指定目录
				boolean currentDir=ftpClient.changeWorkingDirectory(path);
				logger.info("---跳转["+path+"]状态为"+returnResult+"，开始上传文件---"+currentDir);
				if(currentDir==false){
					int name=fileName.indexOf("8");
					if(name==0){
						logger.info("---商户变更上传定位路径----");
						String temp = path;
						List<String> pathList = new ArrayList <String>();
						pathList.add(path);
						int end = 0;
						while(true){
							end = temp.lastIndexOf(File.separator);
							temp = path.substring(0,end);
							if(!ftpClient.changeWorkingDirectory(temp)){
								pathList.add(temp);
							}else{//创建子目录
								for(int i = pathList.size()-1;i>=0;i--){
									boolean createFlag = ftpClient.makeDirectory(pathList.get(i));
									if(!createFlag){
										logger.info("路径创建失败");
									 
									}
									ftpClient.changeWorkingDirectory(pathList.get(i));
								}
								break;
							}
						}
					}else{
						logger.info("---进件上传定位路径----");
						ftpClient.makeDirectory(path);
						returnResult=ftpClient.changeWorkingDirectory(path);
					}
				}
				if(returnResult==true || currentDir == true){
					input= new FileInputStream(file); 
					logger.info("------开始上传图片至ftp----------------");
					returnResult=ftpClient.storeFile(fileName, input); 
					logger.info("------上传图片至ftp结束----------------");
				}
				logger.info("-----上传图片返回结果"+returnResult+"-------------");
			}
		} catch (Exception e) {
			returnResult=false;
			logger.error("----上传图片链接FTP失败----",e);
		}finally {
			if(null!=input){
				try {
						input.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
			if (null != ftpClient) {
				try {
					ftpClient.logout();
					ftpClient.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return returnResult;
	} 
	 
	/**
	 * 上传文件至ftp 目录
	 * */
	public static void copyFile(FTPClient ftp,File file){
		try {
			File file2 = new File(file.getPath());      
			FileInputStream input = new FileInputStream(file2); 
			logger.info("------开始上传文件至ftp----------------");
			ftp.storeFile(file2.getName(), input); 
			logger.info("------上传文件至ftp结束----------------");
			input.close();
		} catch (Exception e) {
			logger.error("======上传文件失败======",e);
		}finally {
			if (null != ftp) {
				try {
					ftp.logout();
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}     
	}
	
	public static void main(String[] args) {
		String a="http://shoudan.freemypay.com:18090/fmposm/upload/showImg.ct?orgs=85278888&mid=17021118550058404001.png&time=1486810597446";
		System.out.println(a.substring(a.indexOf("mid=")+4,a.lastIndexOf("&")));
		String b=a.substring(a.indexOf("mid=")+4,a.lastIndexOf("&"));
		System.err.println(b.substring(0,15));
		System.out.println(b.substring(0, b.indexOf(".")));
		System.out.println(System.currentTimeMillis());
		Random ra=new Random();
		int random=100+ra.nextInt(901);
		System.out.println(random);
		System.out.println("8527_9999".substring(5));
	}
}
